package com.zhentao.controller;

import com.zhentao.service.SqlGenerateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api/sql")
public class SqlController {

    private final SqlGenerateService sqlGenerateService;

    @Autowired
    public SqlController(SqlGenerateService sqlGenerateService) {
        this.sqlGenerateService = sqlGenerateService;
    }

    /**
     * 处理自然语言查询，生成并执行SQL
     */
    @PostMapping("/process")
    public Map<String, Object> processNaturalLanguage(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        if (question == null || question.trim().isEmpty()) {
            return Map.of("success", false, "error", "自然语言查询不能为空");
        }
        
        return sqlGenerateService.processNaturalLanguage(question);
    }

    /**
     * 仅生成SQL，不执行
     */
    @PostMapping("/generate")
    public Map<String, Object> generateSql(@RequestBody Map<String, String> request) {
        try {
            String question = request.get("question");
            if (question == null || question.trim().isEmpty()) {
                return Map.of("success", false, "error", "自然语言查询不能为空");
            }
            
            String sql = sqlGenerateService.convertToSql(question);
            return Map.of(
                "success", true,
                "question", question,
                "generatedSql", sql
            );
        } catch (Exception e) {
            return Map.of(
                "success", false,
                "error", e.getMessage()
            );
        }
    }

    /**
     * 执行指定的SQL
     */
    @PostMapping("/execute")
    public Map<String, Object> executeSql(@RequestBody Map<String, String> request) {
        try {
            String sql = request.get("sql");
            if (sql == null || sql.trim().isEmpty()) {
                return Map.of("success", false, "error", "SQL语句不能为空");
            }
            
            Object result = sqlGenerateService.executeSql(sql);
            return Map.of(
                "success", true,
                "sql", sql,
                "result", result
            );
        } catch (Exception e) {
            return Map.of(
                "success", false,
                "error", e.getMessage()
            );
        }
    }
}
